<template>
  <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
    <el-tab-pane :label="`规则定义`" name="first">
      <!--监控总页面-->
      <div>
        <el-row>
          <el-col :span="6"><p>库名：{{db_name}}</p></el-col>
          <el-col :span="6"><p>表名：{{table_name}}</p></el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-button
              @click="addRuleCollection"
            >新建规则组
            </el-button>
            <!-- 使用组件-->
            <addRuleCollection  v-if="openRuleCollection" ref="addRuleCollection"/>
          </el-col>
        </el-row>
      </div>
      <el-tabs v-model="monitors" type="border-card" @tab-click="handleClickMonitor">
<!--        <div v-for="(item,key) in ruleCollectionList" :key="key">-->
          <el-tab-pane v-for="(item,key) in ruleCollectionList" :label="item.name" :name="item.index" :key="item.id" >
            <el-row>
              <el-col :span="2">
                <el-button type="success"
                  @click="addMonitor"
                >新建规则
                </el-button>
                <!-- 使用组件-->
                <addMonitorInfo  v-if="openAddMonitorInfo" ref="addMonitorInfo"/>
              </el-col>
              <el-col :span="2">
                <el-button type="warning"
                  @click="deleteOneCollection"
                >删除规则组
                </el-button>
              </el-col>
              <el-col :span="2">
                <el-button type="danger"
                           @click="triggerOneCollection"
                >手动触发
                </el-button>
              </el-col>
            </el-row>
            <el-table :data="monitorRuleInfoList" border
                      style="width: 100%">
              <el-table-column
                fixed
                prop="id"
                label="ID"
                width="50">
              </el-table-column>
              <el-table-column
                prop="name"
                label="名称"
                width="150">
              </el-table-column>
              <el-table-column
                prop="analyseType"
                label="分析类型"
                width="150">
              </el-table-column>
              <el-table-column
                prop="ruleLevel"
                label="规则级别"
                width="150">
              </el-table-column>
              <el-table-column
                prop="basePartitionDef"
                label="基准分区表达式"
                :formatter="basePartitionDefString"
              >
              </el-table-column>
              <el-table-column
                prop="checkPartitionDef"
                label="受检分区表达式"
                :formatter="checkPartitionDefString"
              >
              </el-table-column>
              <el-table-column
                prop="fieldsName"
                label="字段名称"
                width="150">
              </el-table-column>
              <el-table-column
                prop="calculateType"
                label="计算类型"
                width="150">
              </el-table-column>
              <el-table-column
                prop="fixedCompareWay"
                label="固定值比较规则"
                width="150">
              </el-table-column>
              <el-table-column
                prop="fixedValue"
                label="固定值"
                width="150">
              </el-table-column>
              <el-table-column
                prop="swingUpper"
                label="波动上限"
                width="150">
              </el-table-column>
              <el-table-column
                prop="swingLower"
                label="波动下限"
                width="150">
              </el-table-column>
              <el-table-column
                fixed="right"
                label="操作"
                >
                <template slot-scope="scope">
                  <el-button type="text" size="small" @click="updateMonitor(scope.row.id)">编辑</el-button>
                  <!-- 使用组件-->
                  <updateMonitor  v-if="openUpdateMonitor" ref="updateMonitor"/>
                  <el-button @click="deleteOneRuleById(scope.row.id)" type="text" size="small">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
<!--        </div>-->
      </el-tabs>
    </el-tab-pane>
    <el-tab-pane :label="`触发记录`" name = "second">
      <triggerList ref="triggerList" />
    </el-tab-pane>
    <el-tab-pane :label="`报警记录`" name = "third">
      <alertList ref="alertList"></alertList>
    </el-tab-pane>
  </el-tabs>

</template>
<script>
import triggerApi from '@/api/monitor/trigger'
import alertApi from '@/api/monitor/alert'
import collectionApi from '@/api/monitor/collection'
import ruleApi from '@/api/monitor/rule'
import previewExecution from '@/views/monitor/previewExecution'
import addMonitorInfo from '@/views/monitor/addMonitorInfo'
import updateMonitor from "@/views/monitor/updateMonitor";
import executePlanList from "@/views/monitor/executePlanList";
import addRuleCollection from '@/views/monitor/addRuleCollection'
import triggerList from '@/views/monitor/triggerList'
import alertList from '@/views/monitor/alertList'
import rule from "@/api/monitor/rule";
// import {parseTime} from '@/utils'

// const now = parseTime(new Date(new Date().getTime()), '{y}-{m}-{d}')
export default {
  components: {previewExecution, addMonitorInfo, updateMonitor, executePlanList,addRuleCollection,triggerList,alertList},
  data() {
    return {
      //默认显示第一个tab（与name有关为first）
      activeName: 'first',
      //默认显示第一个tab（与name有关为索引0）
      monitors:'0',
      index:0,
      //规则集合id
      collectionId:0,
      // 显示窗口
      openRuleCollection:false,
      openDialog: false,
      openAddMonitorInfo: false,
      openUpdateMonitor: false,
      openPlanHistory: false,
      db_name: this.$route.query.schemaName,
      table_name: this.$route.query.tableName,
      tableInfoId: 0,
      who:"admin",
      monitorRuleInfoList: [],
      //规则集合
      ruleCollectionList: [],
      //触发记录集合
      list:[],
      query:{
        page: 1, // 默认页码
        limit: 10, // 每页记录数
      },
      total: 0, // 数据库中的总记录数
      page: 1, // 默认页码
      limit: 10, // 每页记录数
      message:""
    };
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      // this.getGlobalScore()
      this.allRelusCollections()
      this.queryAllRules(this.collectionId);
    },
    // 添加规则集合
    addRuleCollection() {
      this.openRuleCollection = true;
      //调用子页面方法
      this.$nextTick(() => {
        this.$refs.addRuleCollection.init(this.table_name,this.db_name);
      });
    },
    // 按钮方法:弹出添加告警规则页面,以为这里是一个数组，所以需要加索引
    addMonitor() {
      this.openAddMonitorInfo = true;
      //调用子页面方法
      this.$nextTick(() => {
        console.log("22222"+this.collectionId)
        this.$refs.addMonitorInfo[this.index].init(this.table_name,this.db_name,this.collectionId);
      });
    },
    //根据库名和表名查询全部规则集合
    allRelusCollections() {
      collectionApi.allRelusCollections(this.db_name, this.table_name).then((response) => {
        if (response.code == 200) {
          this.ruleCollectionList = response.data
          this.dialogFormVisible = false
          this.collectionId = this.ruleCollectionList[0].id
          this.queryAllRules()
        } else
          "错误";
      });
    },
    //根据规则集合Id查询全部规则
    queryAllRules() {
      ruleApi.allRelus(this.collectionId).then((response) => {
        if (response.code == 200) {
          console.log("----------"+response.data)
          this.monitorRuleInfoList = response.data
          // this.tableInfoId = response.data.id
          this.dialogFormVisible = false
          // this.getList()
        } else
          "错误";
      });
    },
    basePartitionDefString(rows,column) {
      return JSON.stringify(rows.basePartitionDef);
    },
    checkPartitionDefString(rows,column) {
      return JSON.stringify(rows.checkPartitionDef);
    },
    //根据id删除一个规则
    deleteOneRuleById(id) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => { // promise
        // 点击确定，远程调用ajax
        return ruleApi.deleteOneRule(id)
      }).then((response) => {
        // this.fetchData(this.page)
        if (response.code) {
          location.reload()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    //根据id删除一个规则组
    deleteOneCollection(){
      // debugger
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => { // promise
        // 点击确定，远程调用ajax
        return collectionApi.deleteOneCollection(this.collectionId)
      }).then((response) => {
        this.fetchData(this.page)
        if (response.code) {
          location.reload()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    //手动触发
    triggerOneCollection(){
      console.log("000000"+this.collectionId)
      triggerApi.triggerExecute(this.who,this.collectionId).then((response) => {
        if (response.code == 200) {
          this.$notify({
            title: '成功',
            message: '触发成功',
            type: 'success',
            duration: 2000
          })
          location.reload()
        } else
          "失败";
      });
    },
    updateMonitor(id) {
      this.openUpdateMonitor = true;
      //调用子页面方法
      this.$nextTick(() => {
        this.$refs.updateMonitor[this.index].init(id)
      });
    },

    // 当页码发生改变的时候
    changeSize(size) {
      console.log(size)
      this.limit = size
      this.fetchData(1)
    },
// 加载banner列表数据
    fetchData(page = 1) {
      console.log('翻页。。。' + page)
      // 异步获取远程数据（ajax）
      this.page = page
      if(this.message=="trigger"){
        /**
         *触发记录
         */
        triggerApi.getAllTrigger(this.page, this.limit).then(response => {
          // console.log("-----" + this.query.startDate)
          this.listLoading = true
          this.list = response.data.records
          // console.log("========tableData"+this.tableData)
          this.total = response.data.total
          this.listLoading = false

        })
      }else if(this.message == "alert"){
        /**
         *报警记录
         */
        alertApi.getAllAlert(this.page, this.limit).then(response => {
          // console.log("-----" + this.query.startDate)
          this.listLoading = true
          this.list = response.data.records
          console.log("========tableData"+this.list)
          this.total = response.data.total
          this.listLoading = false

        })
      }

    },

    handleClick(tab, event) {

      if (tab.index == 0) {
      } else if (tab.index == 1) {
        this.$refs.triggerList.fetchData()
      } else if(tab.index == 2){
        this.message="alert"
        this.$refs.alertList.fetchData()
      }
      console.log(tab, event);
    },
    handleClickMonitor(tab, event) {
      this.collectionId=0
      this.index = tab.index
      this.collectionId = this.ruleCollectionList[tab.index].id
      console.log("============"+this.collectionId)
      this.queryAllRules();
    },
    handlePlanHistory() {
      this.openPlanHistory = true;
      this.$nextTick(() => {
        this.$refs.executePlanList.init(this.tableInfoId);
      });
    },
    // 按钮方法
    handleDialog() {
      this.openDialog = true;
      this.$nextTick(() => {
        this.$refs.previewExecution.init();
      });
    }
    ,

    // handleFilter() {
    //   this.pageNo = 1
    //   this.handList(this.optionCode)
    // },
    // handleSizeChange(val) {
    //   this.pageSize = val
    //   this.handList(this.optionCode)
    // },
    // handleCurrentChange(val) {
    //   this.pageNo = val
    //   this.handList(this.optionCode)
    // }


  }
}
</script>
<style>
.el-row {
  margin-bottom: 3px;

&
:last-child {
  margin-bottom: 0;
}

:last-child {
  margin-bottom: 0;
}

}
.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>


